//
//  CenterPagingFlowCollectionLayout.m
//  TRoad2
//
//  Created by ZhangYanhua on 14/11/14.
//  Copyright (c) 2014年 Mach. All rights reserved.
//

#import "CenterPagingFlowCollectionLayout.h"

@implementation CenterPagingFlowCollectionLayout

- (void)awakeFromNib
{
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.minimumInteritemSpacing = 5.0f;
}

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset
                                 withScrollingVelocity:(CGPoint)velocity
{
    CGRect targetRect = CGRectMake(proposedContentOffset.x, 0, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
    
    NSArray *array = [super layoutAttributesForElementsInRect:targetRect];
    array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        UICollectionViewLayoutAttributes *item1 = obj1;
        UICollectionViewLayoutAttributes *item2 = obj2;
        
        if (fabs(item1.frame.origin.x - item2.frame.origin.x) <= __FLT_EPSILON__) {
            return NSOrderedSame;
        }
        else if (item1.frame.origin.x < item2.frame.origin.x) {
            return NSOrderedAscending;
        }
        else {
            return NSOrderedDescending;
        }
    }];
    
    CGPoint finalContentOffset = proposedContentOffset;

    for (int i = 0; i < array.count; i++) {
        UICollectionViewLayoutAttributes *curItem = [array objectAtIndex:i];
        
        if (curItem.center.x >= proposedContentOffset.x) {
            finalContentOffset = CGPointMake(curItem.center.x - self.collectionView.bounds.size.width / 2.0f,
                                             proposedContentOffset.y);
            break;
        }
    }

    if (velocity.x > 0.1f && finalContentOffset.x < proposedContentOffset.x) {
        UICollectionViewLayoutAttributes *lastItemAttr = [array lastObject];

        if (lastItemAttr) {
            finalContentOffset = CGPointMake(lastItemAttr.center.x - self.collectionView.bounds.size.width / 2.0f, proposedContentOffset.y);
        }
    }
    else if (velocity.x < -0.1f && finalContentOffset.x > proposedContentOffset.x) {
        UICollectionViewLayoutAttributes *firstItemAttr = [array firstObject];
        if (firstItemAttr) {
            finalContentOffset = CGPointMake(firstItemAttr.center.x - self.collectionView.bounds.size.width / 2.0f, proposedContentOffset.y);
        }
    }

    return finalContentOffset;
}

@end
